package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetMealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealDao setMealDao;

    @Autowired
    private JedisPool jedisPool;

    //注入freemarker对象,用于生成页面
    @Autowired
    private FreeMarkerConfig freeMarkerConfig;

    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //保存setMeal
        setMealDao.add(setmeal);
        Integer id = setmeal.getId();
        setMealAndCheckGroup(id, checkgroupIds);
        String img = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }


    public void generateMobileStaticHtml(){
        //准备模板中所需要的数据
        List<Setmeal> list = setMealDao.findAll();
        generateMobileSetmealListHtml(list);
        generateMobileSetmealDetailHtml(list);

    }

    //生成列表页面
     public  void generateMobileSetmealListHtml( List<Setmeal> list){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("setmealList",list);
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成详情页面(多个)
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        if(list!=null && list.size()>0){
            for (Setmeal setmeal : list) {
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("setmeal",setMealDao.findById(setmeal.getId()));
                generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
            }
        }
    }

    //freemarker通用方法
    public void generateHtml(String template,String htmlPage,Map map){
        Configuration configuration = freeMarkerConfig.getConfiguration();
        Writer writer =null;
        try {
            Template temp = configuration.getTemplate(template);
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outPutPath+"/"+htmlPage)), StandardCharsets.UTF_8));
            temp.process(map,writer);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean pageBean) {

        Integer currentPage = pageBean.getCurrentPage();
        Integer pageSize = pageBean.getPageSize();
        String queryString = pageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setMealDao.findPageByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());

    }

    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }


    @Override
    public Setmeal findById(int id) {
        return setMealDao.findById(id);
    }

    @Override
    public List<Integer> findCheckGroupIdsSetMealId(Integer id) {
        return setMealDao.findCheckGroupIdsSetMealId(id);
    }

    @Override
    public void editOfSetMeal(Setmeal setmeal, Integer[] checkgroupIds) {
        Setmeal set_pro = findById(setmeal.getId());
        //此处获取还未修改的图片路径,用于比对redis做删除操作
        String prv_img = set_pro.getImg();
        System.out.println(prv_img);


        setMealDao.editSetMeal(setmeal);
        Integer now_id = setmeal.getId();

        Boolean sismember = jedisPool.getResource().sismember(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        if (!sismember) {
            jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, prv_img);
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());

        }
        setMealDao.deleteBySetMealId(now_id);

        setMealAndCheckGroup(now_id, checkgroupIds);


    }

    @Override
    public void deleteMeal(Integer id) {
        Setmeal setmeal = findById(id);
        String img = setmeal.getImg();
        //获取图片id用于redis删除操作

        //先删除检查组
        setMealDao.deleteBySetMealId(id);
        //删除套餐
        setMealDao.deleteMeal(id);

        //删除redis中数据
        Boolean sismember = jedisPool.getResource().sismember(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
        if(sismember){
            jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
        }
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setMealDao.findSetmealCount();
    }

    public void setMealAndCheckGroup(Integer mealId, Integer[] checkGroups) {
        if (checkGroups != null && checkGroups.length > 0) {
            for (Integer checkGroupId : checkGroups) {
                Map<String, Integer> map = new HashMap<>();
                map.put("mealId", mealId);
                map.put("checkGroupId", checkGroupId);
                setMealDao.setMealAndCheckGroup(map);
            }
        }
    }
}
